<?php
namespace app\home\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
require_once (APP_PATH . 'api/RewardApi.php');
require_once (APP_PATH . 'api/FinanceApi.php');
class Mail extends Base {
	//空操
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}
	public function _initialize(){
		parent::_initialize();
	}
		/**
		 * 褚天恩
		 * 先进行验证
		 * 看群发消息表当中是否有未接受的消息
		 * 6.6修改  添加已发送查看
		 */
	public function test(){
		$session = session::get();
		$Message = M('Message');
		$Message_all = M('Message_all');
		$where[C("DB_PREFIX").'message.member_id'] = $session['USER_KEY_ID'];
		$count = $Message->where($where)->count();
		$list = $Message->where($where)->select();
		$arr1 = array();
		for($j=0;$j<$count;$j++){
			$message_all_id = $list[$j]['message_all_id'];
			$arr1[] = $message_all_id;
		}
		$group = $Message_all->select();
		$count1 = $Message_all->count();
		for($i=0;$i<$count1;$i++){
			$id = $group[$i]['id'];
			if(!in_array($id,$arr1)){
				$aa = $Message_all->where("id = '$id'")->find();
				$bb['message_all_id'] = $aa['id'];
				$bb['title'] = $aa['title'];
				$bb['type'] = $aa['type'];
				$bb['content'] = $aa['content'];
				$bb['add_time'] = $aa['add_time'];
				$bb['status'] = '0';
				$bb['send_id'] = $aa['u_id'];
				$bb['member_id'] = $session['USER_KEY_ID'];
				$Message->create();
				$Message->add($bb);
			}
		}
	}
	/**
	 * 查看新信件列表页
	 */
	public function index(){
		$session = session::get();
		//收信箱
		$where['s_member_id']=$session['USER_KEY_ID'];
		$where['status'] = array('neq',2);
		$list=M('Message')->where($where)->paginate(20,false,['query'=>input()]);
		$page = $list->render();
		$list = $list->all();
		foreach($list as $k=>$v){
			//是否查看
			$str = explode(",",$list[$k]['mids']);
			if(in_array($session['USER_KEY_ID'],$str)){
				$list[$k]['my_status'] = 1;
			}
			//限制标题内长度
			$list[$k]['title']=mb_substr((strip_tags(html_entity_decode($v['title']))),0,14,'utf-8');
			$list[$k]['content']=mb_substr((strip_tags(html_entity_decode($v['content']))),0,15,'utf-8');
			//获取发件人的用户名
			$res = Db::name('Users')->where(array('userId'=>$list[$k]['f_member_id']))->find();
			$list[$k]['f_name']= $res['account'];
			$list[$k]['pic'] = $res['pic'];
		}
		//dump($list);die();
		$this->assign('list',$list);
		$this->assign('page',$page);
		return $this->fetch();
	}
	//发信箱
	public function inbox(){
		$session = session::get();
		//二级密码验证
		$where['f_member_id'] = $session['USER_KEY_ID'];
		$where['status'] = array('neq',2);
		$list=M('Message')->where($where)->paginate(15,false,['query'=>input()]);
        $page = $list->render();
        $list = $list->all();
		foreach($list as $k=>$v){
			$res = Db::name('Users')->where(array('userId'=>$list[$k]['s_member_id']))->find();
			$list[$k]['s_name']= $res['account'];
			$list[$k]['pic'] = $res['pic'];
		}
		//dump($list);die;
		$this->assign('list',$list);
		$this->assign('page',$page);
		return $this->fetch();
	}
	/**
	 * 已发送查看
	 */
	public function send(){
		
		return $this->fetch();
		
	}
	/**
	 * 信件删除功能
	 */
	public function delete(){
		$id = I('id');
		$res=M('Message')->where("id='".$id."'")->setField('status',2);
		if(in_array(0,$res)){
			$data['info'] = "删除失败";
			$data['status'] = false;
			return json($data);
		}else{
			$data['info'] = "删除成功";
			$data['status'] = true;
			return json($data);
		}
	}
	/**
     * 提交功能
     */
	public function insert(){	
		$session = session::get();
		$title=I('post.title');
		$content=I('post.content');
		$username = I('post.account');
		if(empty($title)||empty($content)||empty($username)){
			$data['status'] = -1;
			$data['info'] = '请填写完整信息';
			return json($data);
		}
		$s_user_id = Db::name('Users')->where(array('loginName'=>$username))->find();
		
		if(!$s_user_id){
			$data['status'] = -3;
			$data['info'] = '收件人不存在';
			return json($data);
		}
		$s_member_id = $s_user_id['userId'];
		$data['f_member_id'] = $session['USER_KEY_ID']; //发件人id
		$data['s_member_id'] = $s_member_id;//收件人id
		$data['title']=$title;
		$data['content']=$content;
		$data['add_time']=time();
		//dump($data);die;
		$r=M('Message')->add($data);
		if($r){
			$data['status'] = 1;
			$data['info'] = '提交成功';
			return json($data);
		}else{
			$data['status'] = -2;
			$data['info'] = '服务器繁忙,请稍后重试';
			return json($data);
		}
	}
	/**
	 * 查看信件详情
	 */
	public function details(){	
		$list = M('Message')->where(array('id'=>I('id')))->find();
		$str = explode(",",$list['mids']);
	
		if(!in_array($_SESSION[USER_KEY_ID],$str)){
			$where['id'] = I('id');
			if(empty($str[0])){
				$str[0] = $_SESSION['USER_KEY_ID'];
			}else{
				$str[] = $_SESSION['USER_KEY_ID'];
			}
			$data['mids'] = implode(',',$str);
			$res =  M('Message')->where($where)->save($data);
		}
		$res = Db::name('Users')->where(array('userId'=>$list['f_member_id']))->find();
		$this->assign('pic',$res['pic']);
		$this->assign('f_name',$res['account']);
		$this->assign('title',$list['title']);
		$this->assign('content',$list['content']);
		$this->assign('add_time',$list['add_time']);
		$this->assign('id',$list['id']);
		return $this->fetch();
	}

	/**
	 * 查看信件详情
	 */
	public function zixun(){
// 		$t1=strtotime($_POST['t1']);
// 		$t2=strtotime($_POST['t2']);
// 		if(!empty($t1) && empty($t2)){
// 			$where['time']=array("between",array($t1,time()));
			
// 		}
// 		if(!empty($t1) && !empty($t2)){
// 			$where['time']=array("between",array($t1,$t2));
// 		}
// 		if(empty($t1) && empty($t2)){
// 			$where['uname']=$_SESSION['username'];
// 		}
// 		if(empty($t1) && !empty($t2)){
// 			$where['time']=array("between",array(0,$t2));
// 		}
		if(!empty($_GET['serviceUser'])){
			$this->assign('serviceUser',I('serviceUser'));//投诉资讯记录
		}
		$where['uid']=$_SESSION['USER_KEY_ID'];
		$service=M('Service');
		$count = $service->where($where)->count();// 查询满足要求的总记录数
		$Page = new \Think\Page($count,10);
		$show       = $Page->show();// 分页显示输出
		$list=$service
		->order("add_time desc")
		->where($where)
		->limit($Page->firstRow.','.$Page->listRows)
		->select();
		 foreach ($list as $k=>$v){
		 	$list[$k]['shouli_status']=$this->shouliStatus($v['shouli_status']);
		 	$list[$k]['huifu_status']=$this->huifuStatus($v['huifu_status']);
		 }
		$this->assign('list',$list);//投诉资讯记录
		$this->assign('page',$show);// 赋值分页输出
		return $this->fetch();
	}
	public function zixunDetail(){
		$id=I('id');
		$service=M('Service')->where("id=$id")->find();
		$this->assign('service',$service);
		return $this->fetch();
	}
	public function del(){
		$id=I('id');
		$re=M('Service')->where("id=$id")->delete();
		if($re){
			$this->success("删除成功");
		}else {
			$this->error("删除失败");
		}
	}
	/**
	 * 受理状态 
	 * @param unknown $status
	 * @return string
	 */
	private function shouliStatus($status){
		switch ($status){
			case 0:$status='未受理';break;
			case 1:$status='已受理';break;
			default:$status='未知状态';
		}
		return  $status;
	}
	/**
	 * 回复状态
	 * @param unknown $status
	 * @return string
	 */
	private function huifuStatus($status){
		switch ($status){
			case 0:$status='未回复';break;
			case 1:$status='已回复';break;
			default:$status='未知状态';
		}
		return  $status;
	}
	/**
	 * 查看信件详情
	 */
	public function zixunAdd(){
		$username=I('username');
		if(!empty($username)){
			$user=$this->getUserByUsername($username);
			if(empty($user)){
				$this->error('查无此人');
			}
			$data['service_uid']=$user['member_id'];
			$data['service_uname']=$user['username'];
		}
		if($_FILES){
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =     3145728 ;// 设置附件上传大小
			$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
			$upload->savePath  =      ''; // 设置附件上传（子）目录
			// 上传文件 
			$info   =   $upload->upload();
			if(!$info) {// 上传错误提示错误信息
			    $this->error($upload->getError());
			}else{// 上传成功 获取上传文件信息
			    foreach($info as $file){
			        $data['pingzheng']="/Uploads/".$file['savepath'].$file['savename'];
			    }
			}
		}
		$session = session::get();
		$data['uname']=$session['USER_KEY'];
		$data['uid']=$session['USER_KEY_ID'];
		$data['title']=I('title');
		$data['content']=I('content');
		$data['add_time']=time();
		$res=M('Service')->add($data);
		if($res){
			$this->success('操作成功');
		}else {
			$this->error('操作失败');
		}
	}
	
	public function huanyuan(){
		$session = session::get();
		$where['s_member_id']=$session['USER_KEY_ID'];
		$where['status'] = array('eq',2);
		$list=M('Message')->where($where)->paginate(15,false,['query'=>input()]);
        $page = $list->render();
        $list = $list->all();
		foreach($list as $k=>$v){
			//是否查看
			$str = explode(",",$list[$k]['mids']);
			if(in_array($session['USER_KEY_ID'],$str)){  
				$list[$k]['my_status'] = 1;
			}
			//限制标题内长度
			$list[$k]['title']=mb_substr((strip_tags(html_entity_decode($v['title']))),0,14,'utf-8');
			$list[$k]['content']=mb_substr((strip_tags(html_entity_decode($v['content']))),0,15,'utf-8');
			//获取发件人的用户名
			$res = Db::name('Users')->where(array('userId'=>$list[$k]['f_member_id']))->find();
			$list[$k]['f_name']= $res['account'];
		}
		//dump($list);die();
		$this->assign('list',$list);
		$this->assign('page',$page);
		return $this->fetch();
	}
	public function doHuanYuan(){
		$id = I('id');
		$res=M('Message')->where("id='".$id."'")->setField('status',1);
		if(in_array(0,$res)){
			$data['info'] = "还原失败";
			$data['status'] = false;
			return json($data);
		}else{
			$data['info'] = "还原成功";
			$data['status'] = true;
			return json($data);
		}
	}
	public function doDel(){
		$id=I('id');
		$re=M('Message')->where("id=$id")->delete();
		if($re){
			$this->success("删除成功");
		}else {
			$this->error("删除失败");
		}
	}
}